package tech.yozo.bamboo.model;

import android.content.Context;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import java.util.Locale;

public class TtsEngine implements TextToSpeech.OnInitListener {
    private TextToSpeech textToSpeech;
    private Context context;

    public void init(Context context) {
        this.context = context;

        if (textToSpeech != null) {
            return;
        }
        textToSpeech = new TextToSpeech(context, this);
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            int result = textToSpeech.setLanguage(Locale.ENGLISH);
            if (result == TextToSpeech.LANG_MISSING_DATA){
                Intent installIntent = new Intent();
                installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                context.startActivity(installIntent);
            }
               else if (result == TextToSpeech.LANG_NOT_SUPPORTED) {
                // TODO 处理不支持的语言
                Log.d("TTS", "不支持该语言TTS");
            }
        } else {
            Log.d("TTS", "TTS初始化失败");
        }
    }

    public void speakOut(String text) {
        textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
    }

    public void release() {
        if (textToSpeech != null) {
            textToSpeech.shutdown();
        }
    }
}
